package com.automannn.atm_back.modules.codeGenerator.controller;


import com.automannn.atm_back.common.api.vo.Result;
import com.automannn.atm_back.common.constant.CommonConstant;
import com.automannn.atm_back.common.system.api.ISysBaseAPI;
import com.automannn.atm_back.modules.codeGenerator.core.pojo.ColumnInfo;
import com.automannn.atm_back.modules.codeGenerator.core.util.StringUtils;
import com.automannn.atm_back.modules.codeGenerator.dto.SourceType;
import com.automannn.atm_back.modules.codeGenerator.entity.*;
import com.automannn.atm_back.modules.codeGenerator.dto.SourceSchemaDTO;
import com.automannn.atm_back.modules.codeGenerator.environment.EnvironmentPerception;
import com.automannn.atm_back.modules.codeGenerator.service.ColumnConfigGroupEntityService;
import com.automannn.atm_back.modules.codeGenerator.service.SchemaEntityService;
import com.automannn.atm_back.modules.codeGenerator.service.TypeMapperEntityService;
import com.automannn.atm_back.modules.codeGenerator.service.TypeMapperGroupEntityService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * (GeneratorColumnConfigGroup)表控制层
 *
 * @author chenkaihai
 * @since 2020-07-12 16:52:30
 */
@RestController
@RequestMapping("codeGenerator/generatorColumnConfigGroup")
@Valid
public class ColumnConfigGroupEntityController {
    /**
     * 服务对象
     */
    @Resource
    private ColumnConfigGroupEntityService columnConfigGroupEntityService;

    @Resource
    private SchemaEntityService schemaEntityService;

    @Resource
    private TypeMapperEntityService typeMapperEntityService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;


    /**
     * 分页查询所有数据
     */
    @GetMapping("/list")
    public Result<IPage<ColumnConfigGroupEntity>> selectAll(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, ColumnConfigGroupEntity generatorColumnGroupConfig) {
        Page<ColumnConfigGroupEntity> page = new Page<>(pageNo, pageSize);
        Result<IPage<ColumnConfigGroupEntity>> result = new Result<IPage<ColumnConfigGroupEntity>>();
        IPage<ColumnConfigGroupEntity> pageList = columnConfigGroupEntityService.queryAll(page, generatorColumnGroupConfig);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable String id) {
        return R.ok(columnConfigGroupEntityService.queryOne(id));
    }

    /**
     * 新增数据
     */
    @PostMapping("/add")
    public Result<ColumnConfigGroupEntity> insert(@RequestBody ColumnConfigGroupEntity generatorColumnConfigGroup) {
        Result<ColumnConfigGroupEntity> result = new Result<>();
        this.columnConfigGroupEntityService.insert(generatorColumnConfigGroup);
        result.success("添加成功！");
        return result;
    }

    /**
     * 修改数据
     */
    @PutMapping("/edit")
    public Result<ColumnConfigGroupEntity> update(@RequestBody ColumnConfigGroupEntity generatorColumnConfigGroup) {
        Result<ColumnConfigGroupEntity> result = new Result<ColumnConfigGroupEntity>();
        this.columnConfigGroupEntityService.update(generatorColumnConfigGroup);
        result.success("修改成功!");
        return result;
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        sysBaseAPI.addLog("删除配置，id： " + id, CommonConstant.LOG_TYPE_2, 3);
        this.columnConfigGroupEntityService.deleteById(id);
        return Result.ok("删除成功");
    }

    /**
     * 删除数据
     *
     * @param ids 主键
     * @return 删除结果
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        sysBaseAPI.addLog("批量删除配置， ids： " + ids, CommonConstant.LOG_TYPE_2, 3);
        this.columnConfigGroupEntityService.deleteBatch(ids);
        return Result.ok("批量删除成功");
    }

    /**
     * 从数据源生成列配置信息
     * * @param tableEntity 代表抽象的数据源
     *
     * @return
     */
    @PostMapping("/buildColumnConfigBySource")
    public Result<?> buildColumnConfigBySource(SourceSchemaDTO sourceSchemaDTO, String typeMapperGroupId) {
        if (SourceType.DATABABE_SOURCE_TYPE.equals(sourceSchemaDTO.getType())) {
            String tableName = sourceSchemaDTO.getName();
            if (StringUtils.isEmpty(tableName)) throw new RuntimeException("表格参数参数为空!");
            List<TableEntity> sourceList = schemaEntityService.queryAllTables(new Page(0,-1), EnvironmentPerception.getNamespace()).getRecords();
            TableEntity tableEntity = sourceList.stream().filter(item -> item.getName().equals(tableName)).findFirst().get();
            if (tableEntity == null) throw new RuntimeException("未找到资源");
            List<ColumnEntity> itemList = schemaEntityService.queryAllColumn(tableName);
            TypeMapperEntity typeMapperEntity = new TypeMapperEntity();
            typeMapperEntity.setTypeMapperGroupId(typeMapperGroupId);
            if (StringUtils.isEmpty(typeMapperGroupId)) throw new RuntimeException("映射参数为空!");
            List typeMapperList = typeMapperEntityService.queryAll(new Page<>(0,-1), typeMapperEntity).getRecords();
            columnConfigGroupEntityService.buildColumnConfigBySource(tableEntity, itemList, typeMapperList);
        }else{
            //todo: 完成 根据数据源 生成  数据源配置接口
            throw new RuntimeException("暂时不支持除数据库源以外的源自动生成配置!");
        }
        return Result.ok("生成配置成功，可前往配置界面进行配置!");
    }
}
